package com.dxf.chepter08

import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}

/**
 *  1
 *
 *
 *
 *
 *
 */
object T99_练习 {


  def main(args: Array[String]): Unit = {
    //1 将sentence中各个字符,通过foldLeft存放到一个ArrayBuffer中
    val sentence = "AAAAAAAAAAAAAABBBBBBBBBBBBBBBCCCCCCCCCCCCDDDDDDD"
    val list = new ArrayBuffer[Char]()
    //t01
    sentence.foldLeft(list)(t01 _)
    println(list)

    //t02
    val map = sentence.foldLeft(Map[Char, Int]())(t02 _)
    //t02_2 使用可变map来进行处理
    val map2 = sentence.foldLeft(mutable.Map[Char, Int]())(t02_2 _)
    println(map, map.getClass)
    println(map2, map2.getClass)

    //t03 统计各个单词出现次数,并按出现次数排序
    val lines = List("atguigu han hello", "atguigu han aaa aaa aaa ccc ddd uuu")

    //
    val map4 = lines.foldLeft(mutable.Map[String, Int]())(t03 _)
    println(map4)




  }


  def t01(arr: ArrayBuffer[Char], char: Char): ArrayBuffer[Char] = {
    arr.append(char)
    arr
  }

  def t02(map: Map[Char, Int], key: Char): Map[Char, Int] = {
    map + (key -> (map.getOrElse(key, 0) + 1))
  }


  def t02_2(map: mutable.Map[Char, Int], key: Char): mutable.Map[Char, Int] = {
    map += (key -> (map.getOrElse(key, 0) + 1))

  }

  //统计各个单词出现次数,并按出现次数排序
  def t03(map: mutable.Map[String, Int], str: String): mutable.Map[String, Int] = {
    val words = str.split(" ")

    for(word <- words){
     map += (word ->  (map.getOrElse(word,0)+1))
    }
   map
  }




}

